import './index.css'
import React, {useState} from "react";

import 'moment/locale/zh-cn';
import { Link } from 'react-router-dom'
import locale from 'antd/es/date-picker/locale/zh_CN'
import { Upload, message, Button, Form, Input, Layout, Menu, Modal, DatePicker, Select } from 'antd';
import { HomeOutlined, SelectOutlined, AimOutlined, HighlightOutlined, SwitcherOutlined, TableOutlined, UploadOutlined } from '@ant-design/icons';
import PubSub from "pubsub-js";
import axios from "axios";

const { Header } = Layout;
const { Option } = Select;

let base64_Url = '';

// 图片转base64格式函数
function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = () => {
      base64_Url = reader.result
      resolve(reader.result)
    }
    reader.onerror = (error) => reject(error)
  })
}


// Upload参数
const props = {
  name: 'file',
  action: '/registrationapi/onlyimg',
  headers: {
    authorization: 'authorization-text',
  },
  beforeUpload(info) {
    let base64Url = getBase64(info);
    const isJPG = info.type === 'image/jpeg';
    if (!isJPG) {
      message.error(`${info.name} 不是jpg格式图片！`);
    }
    return isJPG || Upload.LIST_IGNORE;
  },
  onChange(info) {
    if (info.file.status !== 'uploading') {
      console.log(info.file, info.fileList);
    }
    if (info.file.status === 'done') {
      message.success('选择成功！');
    } else if (info.file.status === 'error') {
      message.error('选择失败！');
    }
  },
};


const Menu_List = () => {
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [isPointModalVisible, setIsPointModalVisible] = useState(false);
  const [isOutlinesModalVisible, setIsOutlinesModalVisible] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [imageUrl, setImageUrl] = useState('');
  const [stage, setStage] = useState(0);    //0代表参考图像，1代表浮动图像
  const [menuOrder, setMenuOrder] = useState(0);
  const [form] = Form.useForm();

  // 设置导航栏的逻辑
  PubSub.subscribe('sendOrderNumber0', (name, orderNumber) => {
    setMenuOrder(orderNumber);
  })

  PubSub.subscribe('sendOrderNumber1', (name, data) => {
    setMenuOrder(data.orderNumber);
    setImageUrl(data.record.image_file);
    if (data.record.stage === '治疗前（参考图像）') {
      setStage(0);
    } else {
      setStage(1);
    }
  })

  PubSub.subscribe('sendOrderNumber2', (name, data) => {
    setMenuOrder(data.orderNumber);
    setImageUrl(data.record.image_file);
    if (data.record.stage === '治疗前（参考图像）') {
      setStage(0);
    } else {
      setStage(1);
    }
  })

  PubSub.subscribe('sendOrderNumber3', (name, orderNumber) => {
    setMenuOrder(orderNumber);
  })

  PubSub.subscribe('sendOrderNumber4', (name, orderNumber) => {
    setMenuOrder(orderNumber);
  })

  PubSub.subscribe('sendOrderNumber5', (name, orderNumber) => {
    setMenuOrder(orderNumber);
  })


  const showModal = () => {
    form.resetFields();
    setIsModalVisible(true);
  };

  const handleOk = (values) => {
    let data = {
      p_name: values.p_name,
      p_sex: values.p_sex,
      p_age: values.p_age,
      doctor: values.doctor,
      stage: values.stage,
      date: values.date,
      image_name: values.image_file,
      image_file: base64_Url,
    }
    let url = '/registrationapi/uploadimg'
    axios.post(url, data, {headers: {'Content-Type': 'application/json'}}
      ).then(res=>{
        if(res.status === 200 && res.data.code === 0){
          message.success('上传成功！')
          PubSub.publish("sendUploadParam", data.p_name);
        } else {
          message.error('上传失败：' + res.data.msg)
        }
    })
    setIsModalVisible(false);
  };

  const handleCancel = () => {
    setIsModalVisible(false);
  };

  const showPointModal = () => {
    setIsPointModalVisible(true);
  }

  const handlePointOk = () => {
    setIsLoading(true)
    let data = { long_image_file: imageUrl, short_image_file: imageUrl.replace(/^data:image\/\w+;base64,/, ""), stage: stage }
    let url = '/registrationapi/intelligentfixedpoint'
    axios.post(url, data, {headers: {'Content-Type': 'application/json'}}
      ).then(res=>{
        if(res.status === 200 && res.data.code === 0){
          PubSub.publish("sendPointImage", res.data)
          message.success(res.data.msg)
          setMenuOrder(2)
          setIsLoading(false)
          setIsPointModalVisible(false)
        } else{
          console.log(res.data.msg)
          message.error(res.data.msg)
        }
    })
  }

  const handlePointCancel = () => {
    setIsPointModalVisible(false);
  }

  const showOutlinesModal = () => {
    setIsOutlinesModalVisible(true);
  }

  const handleOutlinesOk = () => {
    setIsLoading(true)
    let data = { long_image_file: imageUrl, short_image_file: imageUrl.replace(/^data:image\/\w+;base64,/, ""), stage: stage }
    let url = '/registrationapi/intelligentdrawoutlines'
    axios.post(url, data, {headers: {'Content-Type': 'application/json'}}
      ).then(res=>{
        if(res.status === 200 && res.data.code === 0){
          PubSub.publish("sendOutlinesImage", res.data)
          message.success(res.data.msg)
          setIsLoading(false)
          setIsOutlinesModalVisible(false)
        } else{
          console.log(res.data.msg)
          message.error(res.data.msg)
        }
    })
  }

  const handleOutlinesCancel = () => {
    setIsOutlinesModalVisible(false);
  }


  return (
    <Header className="header" style={{ background:'#fff', padding:'0 10px' }}>
      <Modal
        title="输入图片信息"
        visible={isModalVisible}
        onCancel={handleCancel}
        footer={null}
      >
        <Form
          scrollToFirstError
          onFinish={handleOk}
          form={form}
          name="upload_form"
        >
          <Form.Item
            name="p_name"
            label="患者姓名"
            rules={[{ required: true, message: '请输入患者姓名！', whitespace: true }]}
          >
            <Input/>
          </Form.Item>

          <Form.Item
            name="p_sex"
            label="患者性别"
            rules={[{ required: true, message: '请输入患者姓名！', whitespace: true }]}
          >
            <Select style={{ width: 390 }} >
              <Option value="男">男</Option>
              <Option value="女">女</Option>
            </Select>
          </Form.Item>

          <Form.Item
            name="p_age"
            label="患者年龄"
            rules={[{ required: true, message: '请输入患者年龄！', whitespace: true }]}
          >
            <Input/>
          </Form.Item>

          <Form.Item
            name="doctor"
            label="主治医生"
            rules={[{ required: true, message: '请输入患者主治医生！', whitespace: true }]}
          >
            <Input/>
          </Form.Item>

          <Form.Item
            name="stage"
            label="诊疗阶段"
            rules={[{ required: true, message: '请输入患者姓名！', whitespace: true }]}
          >
            <Select style={{ width: 200 }} >
              <Option value="治疗前（参考图像）">治疗前（参考图像）</Option>
              <Option value="治疗后（浮动图像）">治疗后（浮动图像）</Option>
            </Select>
          </Form.Item>

          <Form.Item
            name="date"
            label="拍摄时间"
            rules={[{ required: true, message: '请选择图片拍摄时间！' }]}
          >
            <DatePicker locale={locale} />
          </Form.Item>

          <Form.Item
            name="image_file"
            label="上传图片"
            rules={[{ required: true, message: '请选择需上传的图片！' }]}
          >
            <Upload {...props}>
              <Button icon={<UploadOutlined />}>点击上传</Button>
            </Upload>
          </Form.Item>

          <Form.Item>
            <Button type="primary" htmlType="submit" className="picture-form-submit" >上传</Button>
            <Button className="picture-form-cancel" onClick={handleCancel}>取消</Button>
          </Form.Item>
        </Form>
      </Modal>

      <Modal
        title="智能定点"
        visible={isPointModalVisible}
        onOk={handlePointOk}
        onCancel={handlePointCancel}
        confirmLoading={isLoading}
        okText={"确定"}
        cancelText={"取消"}
      >
        <p style={{color:'#fff'}}>是否要对该图像智能定点？</p>
      </Modal>

      <Modal
        title="绘制轮廓"
        visible={isOutlinesModalVisible}
        onOk={handleOutlinesOk}
        onCancel={handleOutlinesCancel}
        confirmLoading={isLoading}
        okText={"确定"}
        cancelText={"取消"}
      >
        <p style={{color:'#fff'}}>是否要对该图像绘制轮廓？</p>
      </Modal>

      {/*功能导航*/}
      <Menu theme="light" mode="horizontal">
        <Menu.Item key="1">
          <HomeOutlined className="icon_style" />
            <Link to="/index/start/home">首页</Link>
        </Menu.Item>
        <Menu.Item key="2" onClick={showModal} disabled={!(menuOrder === 0 || menuOrder === 1 || menuOrder === 2)}>
          <SelectOutlined className="icon_style" />
          选择图片
        </Menu.Item>
        <Menu.Item key="3" onClick={showPointModal} disabled={!(menuOrder === 1 || menuOrder === 2)}>
          <AimOutlined className="icon_style" />
          智能定点
        </Menu.Item>
        <Menu.Item key="4" onClick={showOutlinesModal} disabled={menuOrder !== 2}>
          <HighlightOutlined className="icon_style" />
          绘制轮廓
        </Menu.Item>
        <Menu.Item key="5">
          <SwitcherOutlined className="icon_style" />
          <Link to="/index/start/registrate">图像配准</Link>
        </Menu.Item>
        <Menu.Item key="6">
          <TableOutlined className="icon_style" />
          <Link to="/index/data">数据列表</Link>
        </Menu.Item>
      </Menu>
    </Header>
  )
};

class Top_Menu extends React.Component{
  render() {
    return (<Menu_List/>)
  }
}

export default Top_Menu;